const express = require('express');
const router = express.Router();
const db = require('../db');

//获取全部数据
router.get('/list', (req, res) => {
    db('select * from todo', null, (err, result) => {
        if (err) throw err;
        res.send({
            status: 0,
            message: '获取数据成功',
            data: result
        });
    });
});

//添加数据
router.post('/add', (req, res) => {

    db('insert into todo set ?', req.body, (err, result) => {
        if (err) {
            console.log(err);
            res.send({
                status: 1,
                message: '添加失败'
            });
        } else {
            res.send({
                status: 0,
                message: '添加成功'
            });
        }
    });
});

//修改数据
router.post('/edit', (req, res) => {

    db('update todo set ? where id=?', [req.body, req.body.id], (err, result) => {
        if (err) {
            console.log(err);
            res.send({
                status: 1,
                message: '修改失败'
            });
        } else {
            res.send({
                status: 0,
                message: '修改成功'
            });
        };
    });
});


//删除数据
router.get('/del/:id', (req, res) => {
    db('delete from todo where id=?', req.params.id, (err, result) => {
        if (err) {
            console.log(err);
            res.send({
                status: 1,
                message: '删除失败'
            });
        } else {
            res.send({
                status: 0,
                message: '删除成功'
            });
        };
    })
})



module.exports = router